package com.hcrazy.manchester.app.jdbc;

import java.util.ArrayList;
import java.util.List;

import com.hcrazy.manchester.app.pojo.PageModel;
import com.hcrazy.manchester.app.pojo.Post;

public class PostDAO extends BaseDAO<Post>{

	/**
	 * 发表回帖
	 * @param post
	 * @throws Exception
	 */
	public void addPost(Post post) throws Exception{
		StringBuffer sb = new StringBuffer();
		sb.append("insert into him_forum_post(");
		sb.append("forumId,topicId,first,author,authorId,subject,postDate,message,postIp,anonymous,type");
		sb.append(") values (");
		sb.append(":forumId,:topicId,:first,:author,:authorId,:subject,:postDate,:message,:postIp,:anonymous,:type");
		sb.append(")");
		
		update(sb.toString(), post);
	}
	
	/**
	 * 批量删除回帖
	 * @param topicIds
	 * @param delOption
	 * @throws Exception
	 */
	public void batchDelete(String[] topicIds ,int delOption) throws Exception{
		String sql = "delete from him_forum_post where topicId = ?";
		List<Object[]> batchArgs = new ArrayList<Object[]>();
		for(String topicId:topicIds){
			Object[] args = new Object[]{topicId};
			batchArgs.add(args);
		}
		this.getJdbcTemplate().batchUpdate(sql, batchArgs);
	}
	
	public List<Post> getPostsByTopicId(long topicId) throws Exception{
		String sql = "select a.*,b.header from him_forum_post a,him_user_info b where topicId = ? and a.authorId = b.userId order by first desc,postDate desc";
		return getList(sql, Post.class, topicId);
	}
	
	/**
	 * 我回复过的帖子列表（客户端功能）
	 * @param model
	 * @param authorId
	 * @return
	 * @throws Exception
	 */
	public PageModel getMyPosts(PageModel model,long authorId) throws Exception{
		StringBuilder querySQL = new StringBuilder("select * from (select a.*,b.`name` from him_forum_post a,him_forum_forum b where a.forumId = b.forumId and first = 0) c");
		StringBuilder countSQL = new StringBuilder("select count(*) from (select a.*,b.`name` from him_forum_post a,him_forum_forum b where a.forumId = b.forumId and first = 0) c");
		StringBuilder whereSQL = new StringBuilder(" where authorId = ? ");
		//最新发表
		whereSQL.append(" order by postDate desc");
		
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(authorId);
		
		return this.getPageModel(model, querySQL, countSQL, whereSQL, paramList, Post.class);
	}
	
	public int getMyPostsCount(long authorId){
		String sql = "select count(*) from him_forum_post a where a.first=0 and a.author=" + authorId;
		return getCount(sql);
	}
}
